<template>
  <div>
    <router-view>
      <div>
        <div style="height: 2vh;"></div>
        <el-card class="box-card">
          <template #header>
            <div style="font-size: 20px; font-weight: 600;">
              <span>医生排班管理</span>
            </div>
          </template>
          <!-- <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane label="本周" name="1"></el-tab-pane>
            <el-tab-pane label="下周" name="2"></el-tab-pane>
          </el-tabs> -->
          <el-table v-loading="loading"
            :data="scheduling_data.slice((currentPage4 - 1) * pageSize4, currentPage4 * pageSize4)" style="width: 100%">
            <el-table-column prop="name" label="医生名称" width="120" align="center" fixed />
            <el-table-column prop="depart_name" label="科室" width="120" align="center" fixed />
            <el-table-column v-for="(item, index) in date_data" :key="index" :label="item.date + item.week"
              align="center">
              <el-table-column prop="state" label="上午" width="90" align="center">
                <template #default="scope">
                  <div v-if="scope.row.shang[index].status == 2"> <span style="color: red;">{{ scope.row.shang[index].num
                  }}</span> / {{ scope.row.shang[index].source }}</div>
                  <div v-if="scope.row.shang[index].status == 1">休息</div>
                  <div v-if="!scope.row.shang[index].status">无</div>
                </template>
              </el-table-column>
              <el-table-column prop="city" label="下午" width="80" align="center">
                <template #default="scope">
                  <div v-if="scope.row.xia[index].status == 2"> <span style="color: red;">{{ scope.row.xia[index].num
                  }}</span>
                    / {{ scope.row.xia[index].source }}</div>
                  <div v-if="scope.row.xia[index].status == 1">休息</div>
                  <div v-if="!scope.row.xia[index].status">无</div>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="130" align="center">
              <template #default="scope">
                <div style="display: flex; align-items: center; justify-content: center">
                  <el-button type="primary" plain size="small" @click="set(scope.row)">设置</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div style="height: 2vh;"></div>
          <div style="display: flex; justify-content: center">
            <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
              :page-sizes="[5, 10, 50, 100]" :small="small" :disabled="disabled" :background="background"
              layout="total, sizes,->, prev, pager, next, jumper" :total="scheduling_data.length" />
          </div>
        </el-card>
      </div>
    </router-view>
    <el-dialog v-model="dialogFormVisible" :title="title + ' 的排班管理'" @close="cancel()" width="55%">
      <div class="log">
        <div class="left" v-if="status">
          <p>医生排班详情</p>
          <p>2024年10月11日</p>
          <p>周三</p>
          <p>上午 <el-switch v-if="status" v-model="top_status" /> </p>
          <p v-if="!status">接诊时间</p>
          <p v-else> <el-time-picker style="width: 80%;" :disabled="!top_status" is-range v-model="top_time"
              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"
              @change="startTime">
            </el-time-picker>
          </p>
          <p v-if="!status">号源</p>
          <p v-else> <el-input-number v-model="top_num" :disabled="!top_status" @change="handleChange" :min="1"
              label="号源"></el-input-number></p>
          <p v-if="!status">接诊人数</p>
          <p v-else> <el-input-number v-model="top_number" :disabled="!top_status" @change="handleChange" :min="0"
              label="号源"></el-input-number>
          </p>
          <i></i>
          <p>下午 <el-switch v-if="status" v-model="bottom_status" /></p>
          <p v-if="!status">接诊时间</p>
          <p v-else> <el-time-picker is-range v-model="bottom_time" :disabled="!bottom_status" range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" @change="endTime">
            </el-time-picker>
          </p>
          <p v-if="!status">号源</p>
          <p v-else> <el-input-number v-model="bottom_num" :disabled="!bottom_status" @change="handleChange" :min="1"
              label="接诊人数"></el-input-number>
          </p>
          <p v-if="!status">接诊人数</p>
          <p v-else> <el-input-number v-model="bottom_number" :disabled="!bottom_status" @change="handleChange" :min="0"
              label="接诊人数"></el-input-number></p>
        </div>
        <div class="right">
          <div style="display: flex;justify-content: space-between;">
            <el-button style="opacity: 0;"></el-button>
            <!-- <el-date-picker v-model="value2" @change="getMonthDays()" type="month" placeholder="选择月"></el-date-picker> -->
            <div>
              <el-button v-if="!status" type="primary" @click="status = true">设置排班</el-button>
              <el-button v-if="status" type="primary" @click="save()">保存设置</el-button>
              <el-button v-if="status" type="primary" @click="quan()">反选</el-button>
              <!-- <el-button v-if="status" type="primary" @click="close()" plain>关闭预约</el-button> -->
            </div>
          </div>
          <div style="display: flex;flex-wrap: wrap;width: 100%;padding-top: 20px;">
            <!-- <div :class="dates <= value2 + '-' + item.days ? 'bar box_date' : 'none box_date'"
              v-for="(item, index) in day" :key="index"> -->
            <div
              :class="item.status && status ? 'barkground box_date' : dates <= item.days ? 'bar box_date' : 'none box_date'"
              v-for="(item, index) in day" :key="index" @click="select(item, index)">
              <p>{{ item.day }}</p>
              <p v-if="item.data && item.data.status == 2"> <span>号源{{ item.data.source || 0 }}</span> </p>
              <p v-if="item.data && item.data.status == 1"> <span>休息</span> </p>
              <p v-if="!item.data"> <span>无</span> </p>
            </div>
          </div>
          <el-button class="close" type="primary" @click="dialogFormVisible = false, status = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { doctor } from '@/api/doctor'
import { scheduling_add, scheduling_list } from '@/api/user'
const activeName = ref('1')
const doctor_data = ref([])
const top_status = ref(true)
const bottom_status = ref(true)
const top_time = ref([])//上午开始时间
const bottom_time = ref()//上午结束时间
const value2 = ref()
const top_num = ref(1)//上午号源
const bottom_num = ref(1)//下午号源
const top_number = ref(1)//上午接诊人数
const bottom_number = ref(1)//下午接诊人数
const status = ref(false)//排班设置状态
const doctor_array = ref([])
const dialogFormVisible = ref(false)
const date_data = ref([])//存放日期
const scheduling_data = ref([])//排班列表
const title = ref('');//标题
const loading = ref(true)
const today = ref()//当前日
const dates = ref()//当前年月
const day = ref([])//指定月份的天数
const pageSize4 = ref(10)
const currentPage4 = ref(1)
const date_status = ref(false)
const formattedDates = ref([]);
const quan = () => {
  for (let i in day.value) {
    day.value[i].status = !date_status.value
  }
  date_status.value = !date_status.value
}
const save = () => {
  ElMessageBox.confirm('是否确认保存设置?', '保存设置', {
    confirmButtonText: '保存设置',
    cancelButtonText: '我再想想',
    type: 'warning',
  })
    .then((res) => {
      if (res == 'confirm') {
        if (!top_time.value || !bottom_time.value) {
          ElMessage({
            type: 'warning',
            message: '请选择开始时间-结束时间',
          });
        } else {
          request()
        }
      } else {
        ElMessage({
          type: 'info',
          message: '您点击了取消',
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '您点击了取消',
      });
    })
}
const request = async () => {
  let array = []
  for (let i in day.value) {
    if (day.value[i].status) {
      array.push({ date: value2.value + '-' + day.value[i].days, depart_id: doctor_array.value.depart_id, time_slot: top_time.value, doctor_id: doctor_array.value.id, time: 1, source: top_num.value, month: "1", status: top_status.value ? 2 : 1, num: top_number.value },
        { date: value2.value + '-' + day.value[i].days, depart_id: doctor_array.value.depart_id, time_slot: bottom_time.value, doctor_id: doctor_array.value.id, time: 2, source: bottom_num.value, month: "1", status: bottom_status.value ? 2 : 1, num: bottom_number.value })
    }
  }
  if (!array) {
    return ElMessage({
      type: 'info',
      message: '请选择日期',
    });
  }
  await scheduling_add({ doctor_id: doctor_array.value.id, arr: JSON.stringify(array) }).then((res) => {
    if (res.code == 1) {
      ElMessage({
        type: 'success',
        message: '保存成功',
      });
      status.value = false
      dialogFormVisible.value = false
      box()
    }
  })
}
const startTime = (value) => {
  let formattedDates = [];
  value.forEach((time) => {
    let inputTime = new Date(time);
    let hours = inputTime.getHours();
    let minutes = inputTime.getMinutes();
    let seconds = inputTime.getSeconds();
    let formattedTime = `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
    formattedDates.push(formattedTime);
  });
  // 在这里处理选中时间的逻辑
  let h = formattedDates[0].split(':')
  let s = formattedDates[1].split(':')
  console.log(s);
  if (h[0] > 12 || s[0] > 12) {
    ElMessage({
      type: 'warning',
      message: '只能选择上午',
    });
    top_time.value = ['Thu Jan 25 2024 08:00:00 GMT+0800 (中国标准时间)', 'Thu Jan 25 2024 08:01:11 GMT+0800 (中国标准时间)'];
  }
};
const endTime = (value) => {
  let formattedDates = [];
  value.forEach((time) => {
    let inputTime = new Date(time);
    let hours = inputTime.getHours();
    let minutes = inputTime.getMinutes();
    let seconds = inputTime.getSeconds();
    let formattedTime = `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
    formattedDates.push(formattedTime);
  });
  // 在这里处理选中时间的逻辑
  let h = formattedDates[0].split(':')
  let s = formattedDates[1].split(':')
  if (h[0] < 12 || s[0] < 12) {
    ElMessage({
      type: 'warning',
      message: '只能选择下午',
    });
    bottom_time.value = ['Thu Jan 25 2024 12:00:00 GMT+0800 (中国标准时间)', 'Thu Jan 25 2024 12:01:11 GMT+0800 (中国标准时间)'];
  }
}
const close = () => {
  ElMessageBox.confirm('是否确认关闭预约?', '关闭预约', {
    confirmButtonText: '关闭预约',
    cancelButtonText: '我再想想',
    type: 'warning',
  })
    .then((res) => {
      ElMessage({
        type: 'success',
        message: '您点击了确认',
      });
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '您点击了取消',
      });
    })
}
const select = (item, index) => {
  if (dates.value > item.days) return ElMessage({
    type: 'warning',
    message: '不能选择过去的日期',
  });
  if (status.value) day.value[index].status = !day.value[index].status
}
// const con = (data) => {
//   console.log(data);
// }
const set = (item) => {
  console.log(item);
  title.value = item.name
  doctor_array.value = item
  dialogFormVisible.value = true
  value2.value = new Date()
  getMonthDays()
}
const box = () => {
  doctor().then((res) => {
    doctor_data.value = res.data
  })
  scheduling_list().then((res) => {
    scheduling_data.value = res.data
    loading.value = false
  })
  let date = new Date();
  let year = date.getFullYear();
  let month = String(date.getMonth() + 1).padStart(2, '0');
  value2.value = date
  let day = date.getDate()
  today.value = day
  dates.value = day
}
//获取指定年月的天数
function getMonthDays() {
  const day_data = ref([])
  let year = value2.value.getFullYear();
  let month = String(value2.value.getMonth() + 1).padStart(2, '0');
  value2.value = year + '-' + month
  var stratDate = new Date(year, month - 1, 1),
    endData = new Date(year, month, 1);
  var days = (endData - stratDate) / (1000 * 60 * 60 * 24);
  for (let i = 0; i < days; i++) {
    let num = i + 1 < 10 ? '0' + (i + 1) : i + 1
    if (doctor_array.value.length != 0) {
      for (let s in doctor_array.value.shang) {
        if (doctor_array.value.shang[s].date == year + '-' + month + '-' + num) {
          day_data.value.push({ day: i + 1, days: num, data: doctor_array.value.shang[s] })
        } else {
          day_data.value.push({ day: i + 1, days: num })
        }
      }
    } else {
      day_data.value.push({ day: i + 1, days: num })
    }
  }
  day.value = removeDuplicates(day_data.value, 'day')
  day.value = removeDuplicate(day.value, 'day')
  day.value = day.value.reverse()
  console.log(day.value);
}
// 一次去重
function removeDuplicates(arr, key) {
  const seen = new Set();
  return arr.filter(obj => {
    const value = obj[key];
    if (seen.has(value) && !obj['data']) {
      return false;
    }
    seen.add(value);
    return true;
  });
}
// 二次去重
function removeDuplicate(arr, key) {
  const seen = new Set();
  return arr.reverse().filter(obj => {
    const value = obj[key];
    if (seen.has(value)) {
      return false;
    }
    seen.add(value);
    return true;
  });
}
box()
getMonthDays()
// 这个方法是获取 今天往后七天的日期和星期(往前几天的话减号就行了)
const getTimeandWeek = () => {
  let date = new Date();
  let year = date.getFullYear();//获取当前年份
  let month = date.getMonth() + 1;//获取当前月
  let dd = new Date(year, month, 0);//获取当月总天数
  let current_month = [];
  let weekList = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  for (let i = 1; i <= dd.getDate(); i++) {
    current_month.push({
      date: year + '-' + month + '-' + i + "号",
      week: weekList[new Date(date.setDate(i)).getDay()],//获取对应日期的星期
    });
  }
  // return weekList 
  date_data.value = current_month
}
getTimeandWeek()
const handleClick = (tab, event) => {
  console.log(tab, event);
}
</script>
<style scoped>
.barkground {
  background-color: #3C90F7;
  color: #ffffff;
}

.none {
  color: #999999;
}

.bar {
  color: #0079FF;
}

.box_date {
  width: 90px;
  height: 90px;
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  border: 1px solid #C3E0FF;
  padding-top: 15px;
}

.box_date p {
  width: 100%;
  height: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.log {
  height: 600px;
  display: flex;
  font-size: 15px;
}

.left {
  width: 250px;
  height: 600px;
  background-color: #FF9138;
  display: flex;
  flex-wrap: wrap;
  padding-top: 20px;

  p {
    width: 90%;
    height: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 20px;
    color: #ffffff;
  }

  i {
    width: 94%;
    height: 1px;
    margin-left: 3%;
    background-color: #ffffff;
  }
}

.right {
  width: 1000px;
  height: 600px;
  margin-left: 20px;
  position: relative;

  .close {
    position: absolute;
    bottom: 10px;
    right: 10px;
  }
}

.over {
  max-height: 55vh;
  overflow: hidden;
  overflow-y: scroll;
}

.box {
  display: flex;
  height: 50px;
}

.border {
  border: 1px solid #C3E0FF;
}

.doctor {
  width: 5%;
  height: 50px;
  color: #0079FF;
  display: flex;
  align-items: center;
  justify-content: center;
}

.block {
  width: 50%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999999;
}

.detart {
  width: 5%;
  height: 50px;
  color: #999999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dateTime {
  width: 12.5%;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.dateTime span {
  color: red;
}

.date {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999999;
  height: 25px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.caozuo {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999999;
}

.caozuo img {
  width: 30px;
  height: 30px;
}

.time_box {
  width: 100%;
  display: flex;
  align-items: center;
}

.time {
  height: 25px;
  width: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999999;
}
</style>